﻿Imports System.Data.SqlClient
Imports System.Xml
Imports System.Data.OleDb

Partial Class ClubListFeed
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Clear()
        Response.ContentType = "application/xml"
        Dim textWriter As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
        textWriter.WriteStartDocument()

        textWriter.WriteStartElement("rss")
        textWriter.WriteAttributeString("version", "2.0")

        textWriter.WriteStartElement("channel")

        Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("ClubsConnectionString").ConnectionString)
        oleDbConn.Open()

        Dim sqlString As String = "SELECT * FROM ClubList ORDER BY CreatedAt DESC"
        Dim cmd As OleDbCommand = New OleDbCommand(sqlString, oleDbConn)
        Dim dr As OleDbDataReader = cmd.ExecuteReader()

        textWriter.WriteElementString("title", "Club List RSS Feed")
        textWriter.WriteElementString("link", "http://" & Request.Url.Host + ":" & Request.Url.Port & "/ClubList.aspx")
        textWriter.WriteElementString("description", "This feed include a list of football clubs added by users")
        textWriter.WriteElementString("language", "en-gb")
        textWriter.WriteElementString("ttl", "5")
        textWriter.WriteElementString("lastBuildDate", String.Format("{0:F}", DateTime.Now))

        Do While dr.Read()
            textWriter.WriteStartElement("item")
            textWriter.WriteElementString("title", dr("ClubName").ToString())
            textWriter.WriteElementString("author", dr("Username").ToString())
            textWriter.WriteElementString("link", "http://" & Request.Url.Host + ":" & Request.Url.Port & "/ClubDetail.aspx?ClubID=" & dr("ID").ToString())

            textWriter.WriteStartElement("guid")
            textWriter.WriteAttributeString("isPermaLink", "true")
            textWriter.WriteString("http://" & Request.Url.Host + ":" & Request.Url.Port & "/ClubDetail.aspx?ClubID=" & dr("ID").ToString())

            textWriter.WriteEndElement()

            textWriter.WriteElementString("pubDate", String.Format("{0:F}", dr("CreatedAt")))

            textWriter.WriteElementString("description", "Club Address: " & dr("Address"))
            textWriter.WriteEndElement()
        Loop

        textWriter.WriteEndElement()
        textWriter.WriteEndElement()

        textWriter.WriteEndDocument()
        textWriter.Flush()
        textWriter.Close()
        Response.End()

        cmd.Dispose()
        oleDbConn.Close()
        oleDbConn.Dispose()
    End Sub

End Class